<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>跟随鼠标移动（大图展示）</title>
    <style type="text/css">
      html,
      body {
        overflow: hidden;
      }
      body,
      div,
      ul,
      li {
        margin: 0;
        padding: 0;
      }
      #box ul {
        width: 768px;
        height: 172px;
        list-style-type: none;
        margin: 10px auto;
      }
      #box li {
        float: left;
        width: 170px;
        height: 170px;
        cursor: pointer;
        display: inline;
        border: 1px solid #ddd;
        margin: 0 10px;
      }
      #box li:hover {
        border: 1px solid #a10000;
      }
      #box li img {
        width: 170px;
        height: 170px;
        vertical-align: top;
      }
      #big {
        position: absolute;
        width: 400px;
        height: 400px;
        border: 2px solid #ddd;
        display: none;
      }
      #big div {
        position: absolute;
        top: 0;
        left: 0;
        width: 400px;
        height: 400px;
        opacity: 0.5;
        filter: alpha(opacity=50);
        /* background: #fff url(img/loading.gif) 50% 50% no-repeat; */
      }
    </style>
  </head>
  <body>
    <div id="box">
      <ul>
        <li><img src="img/shirt_1.jpg" /></li>
        <li><img src="img/shirt_2.jpg" /></li>
        <li><img src="img/shirt_3.jpg" /></li>
        <li><img src="img/shirt_4.jpg" /></li>
      </ul>
    </div>
    <div id="big">
      <div></div>
      <img src="" />
    </div>
    <script>
      let bigEle = document.querySelector("#big");
      let bigImg = document.querySelector("#big img");
      let bigEleWidth = parseFloat(getComputedStyle(bigEle).width);
      //获取div#big的宽度

      let lis = document.querySelectorAll("ul li");
      for (let i = 0; i < lis.length; i++) {
        var li = lis[i];
        //给li添加一个mouseenter事件
        li.addEventListener("mouseenter", function(e) {
          //设置图片的src
          bigImg.src = `img/shirt_${i + 1}_big.jpg`;
          //显示div#big
          bigEle.style.display = "block";
        });
        //添加一个mouseleave事件
        li.addEventListener("mouseleave", function() {
          //影藏div#big
          bigEle.style.display = "none";
        });
        //监听mousemove事件
        li.addEventListener("mousemove", function(e) {
          //获取鼠标相对浏览器视窗的坐标
          let x = e.clientX;
          let y = e.clientY;
          //计算图片的绝对定位Y坐标
          let bigEleY = y + 20;
          //计算图片的绝对定位X坐标
          let bigEleX =
          //如果大图片的有有边界超过窗口
            x + 20 + bigEleWidth > window.innerWidth
              ? x - 20 - bigEleWidth
              : x + 20;
          bigEle.style = `left:${bigEleX}px;top:${bigEleY}px;display:block`;
        });
      }
    </script>
  </body>
</html>
